package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.springmvc.LeaseException;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.RoomInfoMapper;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.atguigu.lease.web.admin.vo.room.RoomDetailVo;
import com.atguigu.lease.web.admin.vo.room.RoomItemVo;
import com.atguigu.lease.web.admin.vo.room.RoomQueryVo;
import com.atguigu.lease.web.admin.vo.room.RoomSubmitVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【room_info(房间信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class RoomInfoServiceImpl extends ServiceImpl<RoomInfoMapper, RoomInfo>
        implements RoomInfoService {

    @Autowired
    private RoomInfoMapper roomInfoMapper;
    @Autowired
    private GraphInfoService graphInfoService;
    @Autowired
    private RoomLabelService roomLabelService;
    @Autowired
    private RoomAttrValueService roomAttrValueService;
    @Autowired
    private RoomFacilityService roomFacilityService;
    @Autowired
    private RoomPaymentTypeService paymentTypeService;
    @Autowired
    private RoomLeaseTermService roomLeaseTermService;
    @Autowired
    private LeaseAgreementService leaseAgreementService;

    @Override
    public void customPage(Page<RoomItemVo> page, RoomQueryVo queryVo) {
        roomInfoMapper.customSelectPage(page,queryVo);
    }

    @Override
    public void custonSaveOrUpdate(RoomSubmitVo roomSubmitVo) {
        //判断是不是更新
        boolean isUpdate = roomSubmitVo.getId() != null;

        saveOrUpdate(roomSubmitVo);

        if (isUpdate){
            deleteSubTables(roomSubmitVo.getId());
        }

        //更新图片
        List<GraphVo> graphVoList = roomSubmitVo.getGraphVoList();
        if (!CollectionUtils.isEmpty(graphVoList)){
            //因为GraphInfo有四个属性，但是GraphVo只有两个，所以要补全再保存，差了所属对象的id和所属对象的类型。
            //创建一个GraphInfo的list，大小为graphVoList的大小。
            ArrayList<GraphInfo> graphInfoArrayList = new ArrayList<>(graphVoList.size());
            //赋值
            for (GraphVo graphVo : graphVoList) {
                //创建一个GraphInfo的对象
                GraphInfo graphInfo = new GraphInfo();
                graphInfo.setName(graphVo.getName());
                graphInfo.setUrl(graphVo.getUrl());
                graphInfo.setItemId(roomSubmitVo.getId());
                graphInfo.setItemType(ItemType.APARTMENT);
                //加到数组
                graphInfoArrayList.add(graphInfo);
            }
            //调用图片的保存
            graphInfoService.saveBatch(graphInfoArrayList);
        }

        //更新标签
        List<Long> labelIds = roomSubmitVo.getLabelInfoIds();
        if (!CollectionUtils.isEmpty(labelIds)){
            ArrayList<RoomLabel> roomLabelArrayList = new ArrayList<>(labelIds.size());
            for (Long labelId : labelIds) {
                RoomLabel roomLabel =
                        RoomLabel.builder()
                                .roomId(roomSubmitVo.getId())
                                .labelId(labelId)
                                .build();

                roomLabelArrayList.add(roomLabel);
            }

            roomLabelService.saveBatch(roomLabelArrayList);
        }

        //更新属性
        List<Long> attrValueIds = roomSubmitVo.getAttrValueIds();
        if (!CollectionUtils.isEmpty(attrValueIds)){
            ArrayList<RoomAttrValue> attrValues = new ArrayList<>(attrValueIds.size());
            for (Long attrValueId : attrValueIds) {
                RoomAttrValue roomAttrValue =
                        RoomAttrValue.builder()
                                .attrValueId(attrValueId)
                                .roomId(roomSubmitVo.getId())
                                .build();

                attrValues.add(roomAttrValue);
            }

            roomAttrValueService.saveBatch(attrValues);
        }

        //更新配套信息
        List<Long> facilityInfoIds = roomSubmitVo.getFacilityInfoIds();
        if (!CollectionUtils.isEmpty(facilityInfoIds)){
            ArrayList<RoomFacility> roomFacilityArrayList = new ArrayList<>(facilityInfoIds.size());
            for (Long facilityInfoId : facilityInfoIds) {
                RoomFacility roomFacility =
                        RoomFacility.builder()
                                .roomId(roomSubmitVo.getId())
                                .facilityId(facilityInfoId)
                                .build();
                roomFacilityArrayList.add(roomFacility);
            }

            roomFacilityService.saveBatch(roomFacilityArrayList);
        }

        //支付方式
        List<Long> paymentTypeIds = roomSubmitVo.getPaymentTypeIds();
        if (!CollectionUtils.isEmpty(paymentTypeIds)){
            ArrayList<RoomPaymentType> roomPaymentTypeArrayList = new ArrayList<>(paymentTypeIds.size());
            for (Long facilityInfoId : paymentTypeIds) {
                RoomPaymentType roomFacility =
                        RoomPaymentType.builder()
                                .roomId(roomSubmitVo.getId())
                                .paymentTypeId(facilityInfoId)
                                .build();
                roomPaymentTypeArrayList.add(roomFacility);
            }

            paymentTypeService.saveBatch(roomPaymentTypeArrayList);
        }

        //租期
        List<Long> leaseTermIds = roomSubmitVo.getLeaseTermIds();
        if (!CollectionUtils.isEmpty(leaseTermIds)){
            ArrayList<RoomLeaseTerm> leaseTermArrayList = new ArrayList<>(leaseTermIds.size());
            for (Long facilityInfoId : leaseTermIds) {
                RoomLeaseTerm roomFacility =
                        RoomLeaseTerm.builder()
                                .roomId(roomSubmitVo.getId())
                                .leaseTermId(facilityInfoId)
                                .build();
                leaseTermArrayList.add(roomFacility);
            }

            roomLeaseTermService.saveBatch(leaseTermArrayList);
        }
    }

    @Override
    public RoomDetailVo customGetById(Long id) {
        return roomInfoMapper.customGetById(id);
    }

    @Override
    public void customRemoveById(Long id) {
        LambdaQueryWrapper<LeaseAgreement> lambdaQueryWrapper
                = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LeaseAgreement::getRoomId,id);
        long count = leaseAgreementService.count(lambdaQueryWrapper);
        if (count>0){
            throw new LeaseException(ResultCodeEnum.DELETE_ERROR);
        }

        //如果没有子表就删除
        deleteSubTables(id);
        //删除公寓信息
        removeById(id);
    }

    //删除子表
    private void deleteSubTables(long roomId){
        //删除图片（根据所属对象类型，图片id）
        LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper
                =new LambdaQueryWrapper<>();
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId,roomId);
        graphInfoService.remove(graphInfoLambdaQueryWrapper);

        //删除配套信息
        LambdaQueryWrapper<RoomFacility> facilityLambdaQueryWrapper
                = new LambdaQueryWrapper<>();
        facilityLambdaQueryWrapper.eq(RoomFacility::getFacilityId,roomId);
        roomFacilityService.remove(facilityLambdaQueryWrapper);

        //删除标签关系
        LambdaQueryWrapper<RoomLabel> labelLambdaQueryWrapper
                = new LambdaQueryWrapper<>();
        labelLambdaQueryWrapper.eq(RoomLabel::getRoomId,roomId);
        roomLabelService.remove(labelLambdaQueryWrapper);

        LambdaQueryWrapper<RoomAttrValue> attrQueryMapper = new LambdaQueryWrapper<>();
        attrQueryMapper.eq(RoomAttrValue::getRoomId, roomId);
        roomAttrValueService.remove(attrQueryMapper);

        LambdaQueryWrapper<RoomPaymentType> paymentQueryWrapper = new LambdaQueryWrapper<>();
        paymentQueryWrapper.eq(RoomPaymentType::getRoomId, roomId);
        paymentTypeService.remove(paymentQueryWrapper);

        LambdaQueryWrapper<RoomLeaseTerm> termQueryWrapper = new LambdaQueryWrapper<>();
        termQueryWrapper.eq(RoomLeaseTerm::getRoomId, roomId);
        roomLeaseTermService.remove(termQueryWrapper);

    }
}




